/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.compress

import cool.taomu.box.compress.impl.GZipCompress
import cool.taomu.box.compress.impl.TarCompress
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.io.IOUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class TarGzUtils {
	static final Logger LOG = LoggerFactory.getLogger(TarGzUtils);

	def static void zcvf(String src,String dest) {
		try(var f = new FileOutputStream(dest)) {
			try(var tar = new TarCompress(new GZipCompress)) {
				var taos = tar.compression(new BufferedOutputStream(f)) as TarArchiveOutputStream;
				addFilesToTarGz(src,"",taos);
			}
		}
	}

	private def static void addFilesToTarGz(String src, String parent,
		TarArchiveOutputStream tarAos) throws IOException{
		var File file = new File(src);
		var String name = parent + file.getName();
		tarAos.putArchiveEntry(new TarArchiveEntry(file, name));
		if (file.isFile()) {
			try(var fis = new FileInputStream(file)) {
				var BufferedInputStream bis = new BufferedInputStream(fis);
				IOUtils.copy(bis, tarAos);
				tarAos.closeArchiveEntry();
				bis.close();
			}
		} else if (file.isDirectory()) {
			tarAos.closeArchiveEntry();
			for (File f : file.listFiles()) {
				addFilesToTarGz(f.getAbsolutePath(), name + File.separator, tarAos);
			}
		}
	}

}
